import { createStore } from "vuex";
import { toRaw } from "vue";
const token = localStorage.getItem("token");
let accountInfo = localStorage.getItem("accountInfo");
if (accountInfo) {
  accountInfo = JSON.parse(accountInfo);
}
const initTag = [
  {
    path: "/",
    name: "reward",
    meta: {
      linkName: "收益数据",
      iconName: "",
      index: "1",
    },
  },
];
let menuTags = localStorage.getItem("menuTags")
  ? JSON.parse(localStorage.getItem("menuTags"))
  : initTag;

export default createStore({
  state: {
    //登录状态
    isLogin: token ? true : false,
    token: token,
    //账号信息
    accountInfo: accountInfo,
    //标签栏
    menuTags: menuTags,
    //用户信息
    info: {},
  },
  mutations: {
    setInfo(state, payload) {
      state.info = payload;
    },
    setIsLogin(state, payload) {
      state.isLogin = payload;
    },
    setToken(state, payload) {
      state.token = payload;
    },
    setAccountInfo(state, payload) {
      state.accountInfo = payload;
    },
    setMenuTags(state, { tag, method }) {
      let index = state.menuTags.findIndex((_tag) => _tag.path == tag.path);
      switch (method) {
        case "add":
          state.menuTags.push(tag);
          break;
        case "remove":
          if (index != -1) {
            state.menuTags.splice(index, 1);
          }
          break;
        case "clear":
          state.menuTags = initTag;
          break;
        default:
          break;
      }
      localStorage.setItem("menuTags", JSON.stringify(toRaw(state.menuTags)));
    },
  },
  actions: {
    changeAccountInfo({ commit }, accountInfo) {
      localStorage.setItem("accountInfo", accountInfo);
      if (accountInfo) {
        commit("setAccountInfo", JSON.parse(accountInfo));
      }
    },
    login({ commit }, token) {
      commit("setToken", token);
      commit("setIsLogin", true);
      localStorage.setItem("token", token);
    },
    logout({ commit }) {
      commit("setToken", "");
      commit("setIsLogin", false);
      localStorage.removeItem("token");
    },
  },
  modules: {},
});
